﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SDT.DataService.Contexts;
using SDT.DataService.Repositories;
using SDT.DataService;
using SDT.Libraries.Utilities;
using System.IO;

namespace SDT.DataService.Services
{
    public class NewsService : IService<Article>
    {
        #region Field

        private IRepository<Article> repository;

        #endregion
        
        public enum Status { NA = 0, NEW = 1, UPDATE_CONTENT = 2 };

        #region Constructor
        public NewsService()
            : this(new Repository<Article>())
        {
        }

        public NewsService(IRepository<Article> repository)
        {
            this.repository = repository;

        }
        #endregion

        #region Store Procedure
        public int WC_Insert(int ChannelId,
        int PageId,
        int CateID,
        int NewsType,
        DateTime CreatedDate,
        string Title,
        string Lead,
        string Content,
        string FTS,
        bool PubYN,
        string OriginalUrl, string ImageDesc,
        string ManualTitle,
        string MetaTitle,
        string MetaDescription,
        string MetaKeyword,
        string MetaTags,
        byte status)
        {
            NewsContext contextObj = new NewsContext();

            try
            {
                return contextObj.sp_WC_Article_Insert((int)ChannelId, (int)PageId, (int)CateID, (int)NewsType, CreatedDate, Title, Lead, Content, FTS, PubYN, OriginalUrl, ImageDesc, status, ManualTitle, MetaTitle, MetaDescription, MetaKeyword, MetaTags);
            }
            catch (Exception ex)
            {

                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "NewsService.WC_Insert", PageId.ToString() + "--------" + ex.Message));
                return 0;
            }
            finally { contextObj.Dispose(); }


        }

        public IList<sp_WC_GetPreviousArticleResult> GetPreviousArticle(int articleID)
        {
            NewsContext contextObj = new NewsContext();

            try
            {
                return contextObj.sp_WC_GetPreviousArticle((int)articleID).ToList();
            }
            catch (Exception ex)
            {
                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "NewsService.GetPreviousArticle", ex.Message));

            }
            finally { contextObj.Dispose(); }
            return null;


        }
        public int sp_ad_article_update_metakey_tag(int id, string metaTag)
        {
            NewsContext contextObj = new NewsContext();

            try
            {
                return contextObj.sp_ad_article_update_metakey_tag(id, metaTag);
            }
            catch (Exception ex)
            {
                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "NewsService.Insert Tag Ranking Error Exception", id.ToString() + "-------" + ex.Message));
                return 0;
            }
            finally { contextObj.Dispose(); }

        }

        /// <summary>
        /// trong trường hợp là save file vào thư mục thì sao
        /// </summary>
        /// <param name="id"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private int sp_WC_News_ReplaceImage(int id, string content)
        {
            NewsContext contextObj = new NewsContext();
            try
            {
                return contextObj.sp_WC_News_ReplaceImage(id, content, (byte)Status.UPDATE_CONTENT);
            }
            catch
            {

                return 0;
            }
            finally { contextObj.Dispose(); }

        }

        #endregion

        #region Check Duplicate
        /// <summary>
        /// Create Date : 23-09-2010
        /// </summary>
        /// <param name="DupArticleID">La tin dang lai</param>
        /// <param name="ArticleID">La tin goc</param>
        /// <param name="detect"></param>
        /// <returns></returns>
        public int DuplicatedArticleInsert(int DupArticleID, int ArticleID, double detect)
        {
            NewsContext contextObj = new NewsContext();
            try
            {
                return contextObj.sp_WC_DuplicatedArticle_Insert(ArticleID, DupArticleID, detect);
            }
            catch
            {

                return 0;
            }
            finally { contextObj.Dispose(); }

        }
        #endregion

        #region Replace Content Image

        public string GetContentByPageID(int id)
        {
            NewsContext contextObj = new NewsContext();
            try
            {
                sp_WC_News_GetByIDResult newsObj = contextObj.sp_WC_News_GetByID(id).FirstOrDefault();
                return newsObj.FullContent;
            }
            catch (Exception ex)
            {
                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "NewsService.GetContentByPageID", ex.Message));

            }
            finally { contextObj.Dispose(); }
            return string.Empty;

        }

        public IList<Spider_LinkDownload> GetLinkByPageID(int Id)
        {

            try
            {
                return (new LinkDownloadService()).GetAll().Where(itm => itm.PageID == Id).ToList();
            }
            catch (Exception ex)
            {
                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "NewsService.GetLinkByPageID", ex.Message));

            }
            finally { }
            return null;

        }
        /// <summary>
        /// Author: TungNX
        /// Get Nội dung của trang về
        /// Get danh sách tất cả các link download của một bài viết
        /// Tạo cặp khóa cần thay thế cho file duong dan goc và duong dan file
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int ReplaceAllOldImage(int id)
        {
            string content = GetContentByPageID(id);
            lock (this)
            {
                StringReplacer strObj = new StringReplacer(content);

                IList<Spider_LinkDownload> l = GetLinkByPageID(id);
                foreach (var itm in l)
                    strObj.AddStringReplacementPair(itm.LinkURL, itm.PathSaveFile);

                content = strObj.GetReplacedContent();
                //update DB
                if (!string.IsNullOrEmpty(content))
                    // ở đây mới cập nhật file
                    return sp_WC_News_ReplaceImage(id, content);
                //
                else return 0;
            }

        }
        /// <summary>
        /// Author: TungNX
        /// Date : 13/04/2011
        /// </summary>
        /// <returns></returns>
        public string GetContentInFile(string DataFile)
        {
            var w = (new FileInfo(DataFile)).OpenText();            
            return w.ToString();            
        }


        public string SetContentHaveAbsIMG(IList<string> orl, IList<string> desl, string content)
        {
            lock (this)
            {
                StringReplacer strObj = new StringReplacer(content);

                for (int i = 0; i < orl.Count; i++)
                    strObj.AddStringReplacementPair(orl[i], desl[i]);
                content = strObj.GetReplacedContent();

                return content;
            }
        }


        #endregion

        #region IService<Article> Members

        public IQueryable<Article> GetAll()
        {
            return repository.GetAll();
        }

        public bool Update(Article entity)
        {
            throw new NotImplementedException();
        }

        public bool Create(Article entity)
        {
            throw new NotImplementedException();
        }

        public bool Delete(Article entity)
        {
            throw new NotImplementedException();
        }

        #endregion
      
        // Created by: Vietlv
        // Created Date: 01/07/2011
        // Description: Insert Articles to other database;

        public int InsertArticleToOtherDatabase(int ChannelId, int PageId, int CateID, int NewsType, DateTime CreatedDate, string Title, string Lead, string Content, string FTS, bool PubYN, string OriginalUrl, string ImageDesc, string ManualTitle, string MetaTitle, string MetaDescription, string MetaKeyword, string MetaTags, byte status,string source)
        {
            FTC_BDSDataContext eDataContext = new FTC_BDSDataContext();
            SystemSpiderDataContext db = new SystemSpiderDataContext();
            var cat = db.Spider_CateMaps.Where(e => e.OrCategoryID == CateID).Select(e => e.DesCategoryID).FirstOrDefault();
            var isCurrentArticle = eDataContext.Articles.Where(e => e.PageID == PageId).FirstOrDefault();
            var dateEquals = DateTime.Now.AddDays(-5);
            var listTitle = eDataContext.Articles.Where(e => e.AddDate >= dateEquals).Select(e => e.Title).ToList();
            if (isCurrentArticle != null)
            {
                try
                {
                    isCurrentArticle.ArticleContent = Content;
                    isCurrentArticle.CatID = cat >0? cat: 31;
                    isCurrentArticle.AddDate = CreatedDate;
                   // isCurrentArticle.ImagePath = ImageDesc;
                    isCurrentArticle.MetaDescription = MetaDescription;
                    isCurrentArticle.MetaKeyword = MetaKeyword;
                    isCurrentArticle.FTS = FTS;
                    isCurrentArticle.Title = Title;
                    isCurrentArticle.PubYN = false;
                    isCurrentArticle.VipYN = false;
                    isCurrentArticle.Summary = Lead;
                    isCurrentArticle.PageID = PageId;
                    isCurrentArticle.MetaTag = MetaTags;
                    isCurrentArticle.MetaDescription = MetaDescription;
                    isCurrentArticle.MetaKeyword = MetaKeyword;
                    isCurrentArticle.Source = source;
                    isCurrentArticle.Status = status;

                    eDataContext.SubmitChanges();
                    return 1;
                }
                catch
                {
                    return 0;
                }
                finally
                {
                    eDataContext.Dispose();
                }

            }
            else
            {
                if (!listTitle.Contains(Title))
                {
                    try
                    {

                        var itemArticle = new Article();
                        itemArticle.ArticleContent = Content;
                        itemArticle.CatID = cat > 0 ? cat : 31;
                        itemArticle.AddDate = CreatedDate;
                        itemArticle.ImagePath = ImageDesc;
                        itemArticle.MetaDescription = MetaDescription;
                        itemArticle.MetaKeyword = MetaKeyword;
                        itemArticle.FTS = FTS;
                        itemArticle.Title = Title;
                        itemArticle.PubYN = false;
                        itemArticle.VipYN = false;
                        itemArticle.Summary = Lead;
                        itemArticle.PageID = PageId;
                        itemArticle.MetaTag = MetaTags;
                        itemArticle.MetaDescription = MetaDescription;
                        itemArticle.MetaKeyword = MetaKeyword;
                        itemArticle.AddBy = new Guid("29c7642c-5dba-4462-86a9-9e90d692efa7");
                        itemArticle.Source = source;
                        itemArticle.Status = status;
                        eDataContext.Articles.InsertOnSubmit(itemArticle);
                        eDataContext.SubmitChanges();
                        return 1;
                    }
                    catch
                    {
                        return 0;
                    }
                    finally
                    {
                        eDataContext.Dispose();
                    }
                }
                else {
                    return 1;
                }
            }
        }
    }
}
